package com.smart.draw.plantuml.controllers;

import com.smart.draw.plantuml.UrlHelper;
import com.smart.draw.plantuml.common.PlantUmlType;
import com.smart.draw.plantuml.service.PlantUmlTypeService;
import com.smart.draw.plantuml.service.TranscoderService;
import com.smart.draw.plantuml.service.UrlService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author xiaoqiang
 * @Version UmlController.java, v 0.1 2025年08月26日 14:28 xiaoqiang
 * @Description: TODO
 */
@Controller
@RequestMapping("uml")
public class UmlController {

    @Resource
    private TranscoderService transcoderService;


    @Resource
    private UrlService urlService;

    @Resource
    private PlantUmlTypeService plantUmlTypeService;



    @PostMapping("/async")
    public ResponseEntity<Map<String, String>> renderAsync(@RequestParam String source) {
        Map<String, String> response = new HashMap<>();
        try {
            // 使用 PlantUML 工具生成 encodedSource
            String encodedSource = transcoderService.encode( source);//Compression(source.getBytes("UTF-8"));
            response.put("encodedSource", encodedSource);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("error", e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    @GetMapping("{encodedSource:.*}")
    public String show(
            HttpServletRequest request,
            @PathVariable("encodedSource") String encodedSource,
            @CookieValue(value = "layout", required = false) String layout,
            @RequestParam(value = "type", required = false) String type,
            Model model) {

        PlantUmlType plantUmlType = PlantUmlType.getByType(type);
        String generatedUrl = urlService.generatePngUrl(request,encodedSource);


        // 传给模板
        model.addAttribute("generatedUrl", generatedUrl);
        model.addAttribute("currentUrl", UrlHelper.getCurrentUrl(request));
        model.addAttribute("baseUrl", UrlHelper.getBaseUrl(request));
        var source = transcoderService.decode(encodedSource);
        model.addAttribute("encodedSource", encodedSource);
        model.addAttribute("source", source);
        //model.addAttribute("plantUmlTypes", plantUmlTypeService.getPlantUmlTypes());
        //model.addAttribute("currentType", plantUmlType.getType());
        if ("left-right".equals(layout)) {
            return "editor/left-right";
        } else {
            return "editor/fluid";
        }
    }

    @PostMapping
    public String create(@RequestParam("source") String source) {
        return "redirect:uml/" + transcoderService.encode(source);
    }

    @PostMapping("recover")
    public String recover(@RequestParam("url") String url) throws IOException {
        return "redirect:" + extractEncodedSource(url);
    }

    private String extractEncodedSource(String url) throws MalformedURLException {
        var path = new URL(url).getPath();
        var segments = path.split("/");
        if (segments.length > 2) {
            return segments[segments.length - 1];
        }
        return "SyfFKj2rKt3CoKnELR1Io4ZDoSa70000";
    }

}